package logger

import (
	"fmt"
	"github.com/fatih/color"
	"github.com/sirupsen/logrus"
	"os"
	"strconv"
	"time"
)


type CustomTextFormatter struct {
	ForceColors   bool         // 强制使用颜色
	ColorInfo     *color.Color // Info级别日志颜色
	ColorWarning  *color.Color // Warn级别日志颜色
	ColorError    *color.Color // Error级别日志颜色
	ColorCritical *color.Color // Critical级别日志颜色
	EnvironmentOverrideColors bool
	TimestampFormat string
	FullTimestamp bool
	DisableLevelTruncation bool
}

// Format 自定义Format方法
func (f *CustomTextFormatter) Format(entry *logrus.Entry) ([]byte, error) {
	if f.ForceColors {
		// 如果强制使用颜色，则根据日志级别打印带有颜色的输出
		switch entry.Level {
		case logrus.InfoLevel:
			f.ColorInfo.Println(formatMessageWithTimestamp(entry))
		case logrus.WarnLevel:
			f.ColorWarning.Println(formatMessageWithTimestamp(entry))
		case logrus.ErrorLevel:
			f.ColorError.Println(formatMessageWithTimestamp(entry))
		case logrus.FatalLevel, logrus.PanicLevel:
			f.ColorCritical.Println(formatMessageWithTimestamp(entry))
		default:
			f.PrintColored(entry)
		}
		return nil, nil
	} else {
		// 否则，返回默认格式化输出
		return f.formatDefault(entry)
	}
}

// 格式化默认输出的方法
func (f *CustomTextFormatter) formatDefault(entry *logrus.Entry) ([]byte, error) {
	timestamp := entry.Time.Format(time.DateTime)
	level := entry.Level.String()
	msg := entry.Message

	return []byte(fmt.Sprintf("[%s] %s %s\n", level, timestamp, msg)), nil
}

// PrintColored 打印带颜色的日志输出的方法
func (f *CustomTextFormatter) PrintColored(entry *logrus.Entry) {
	levelColor := color.New(color.FgCyan, color.Bold)
	levelText := levelColor.Sprintf("%-6s", entry.Level.String())

	msg := levelText + " " + formatMessageWithTimestamp(entry)
	if entry.HasCaller() {
		msg += " (" + entry.Caller.File + ":" + strconv.Itoa(entry.Caller.Line) + ")"
	}

	fmt.Fprintln(color.Output, msg)
}

// 格式化消息并添加时间戳
func formatMessageWithTimestamp(entry *logrus.Entry) string {
	timestamp := entry.Time.Format(time.DateTime)
	level := entry.Level.String()
	return "[" + level + "]" + timestamp + " " + entry.Message
}

func CreateLogger() *logrus.Logger {
	var log_ = logrus.StandardLogger()
	//// 日志级别为info
	//log_.SetLevel(logrus.InfoLevel)
	//// 日志级别为warn
	//log_.SetLevel(logrus.WarnLevel)
	//// 日志级别为trace
	//log_.SetLevel(logrus.TraceLevel)
	// 设置日志级别
	var level logrus.Level = logrus.InfoLevel  // 日志级别为info
	//var level logrus.Level = logrus.WarnLevel  // 日志级别为warn
	//var level logrus.Level = logrus.ErrorLevel  // 日志级别为error
	//var level logrus.Level = logrus.TraceLevel  // 日志级别为trace
	//var level logrus.Level = logrus.DebugLevel  // 日志级别为debug
	log_.SetLevel(level)
	// 日志格式为json格式
	//log_.SetFormatter(&logrus.JSONFormatter{
	//	TimestampFormat: "2006-01-02 15:04:05",
	//})
	//log_.SetFormatter(&logrus.TextFormatter{
	//	ForceColors:               true,
	//	EnvironmentOverrideColors: true,
	//	TimestampFormat:           "2006-01-02 15:04:05", //时间格式
	//	FullTimestamp:true,  // 显示完整时间
	//	DisableLevelTruncation:true,
	//})
	log_.Formatter = &CustomTextFormatter{
		ForceColors:   true,
		ColorInfo:     color.New(color.FgBlue),
		ColorWarning:  color.New(color.FgYellow),
		ColorError:    color.New(color.FgRed),
		ColorCritical: color.New(color.BgRed, color.FgWhite),
		EnvironmentOverrideColors: true,
		TimestampFormat:           "2006-01-02 15:04:05", //时间格式
		FullTimestamp:true,  // 显示完整时间
		DisableLevelTruncation:true,
	}
	//定位行号, 显示打印日志文件和位置
	log_.SetReportCaller(true)

	////logfile, _ := os.OpenFile("./log.log", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)
	////log_.SetOutput(logfile) //默认为os.stderr
	////log_.SetOutput(io.MultiWriter(os.Stdout, logfile)) // 输出到多个位置
	log_.SetOutput(os.Stdout)

	return log_
}

type LoggerFuncHandle func(args ...interface{})

func CreateLoggerTrace() LoggerFuncHandle {
	var log_ = CreateLogger()
	log_.SetLevel(logrus.InfoLevel)
	var handle LoggerFuncHandle = log_.Traceln
	return handle
}

func CreateLoggerDebug() LoggerFuncHandle {
	var log_ = CreateLogger()
	log_.SetLevel(logrus.DebugLevel)
	var handle LoggerFuncHandle = log_.Debugln
	return handle
}

func CreateLoggerInfo() LoggerFuncHandle {
	var log_ = CreateLogger()
	log_.SetLevel(logrus.InfoLevel)
	var handle LoggerFuncHandle = log_.Infoln
	return handle
}

func CreateLoggerWarn() LoggerFuncHandle {
	var log_ = CreateLogger()
	log_.SetLevel(logrus.WarnLevel)
	var handle LoggerFuncHandle = log_.Warnln
	return handle
}

func CreateLoggerError() LoggerFuncHandle {
	var log_ = CreateLogger()
	log_.SetLevel(logrus.ErrorLevel)
	var handle LoggerFuncHandle = log_.Errorln
	return handle
}

type LoggerOutParams struct {
	Level logrus.Level
}

type LoggerOption func(*LoggerOutParams)

func SetLevel(level logrus.Level) LoggerOption {
	return func(e *LoggerOutParams) {
		e.Level = level
	}
}

func CreateLoggerOut(opts ...LoggerOption) LoggerFuncHandle {
	// 初始化默认值
	defaultParams := LoggerOutParams{
		Level: logrus.InfoLevel,
	}
	// 依次调用opts函数列表中的函数，为结构体成员赋值
	for _, opt := range opts {
		opt(&defaultParams)
	}
	var log_ = CreateLogger()
	log_.SetLevel(defaultParams.Level)
	var handle LoggerFuncHandle = log_.Infoln
	if(defaultParams.Level == logrus.DebugLevel) {
		handle = log_.Debugln
	}
	if(defaultParams.Level == logrus.TraceLevel) {
		handle = log_.Traceln
	}
	if(defaultParams.Level == logrus.WarnLevel) {
		handle = log_.Warnln
	}
	if(defaultParams.Level == logrus.ErrorLevel) {
		handle = log_.Errorln
	}
	if(defaultParams.Level == logrus.InfoLevel) {
		handle = log_.Infoln
	}

	return handle
}

func TestPrint() {
	//logger := CreateLogger()

	//logger.Println("hello")
	//logger.Printf("hello")

	//logger.SetLevel(logrus.InfoLevel)
	//logger.Infoln("hello")

	//logger.SetLevel(logrus.DebugLevel)
	//logger.Debugln("hello")

	//logger.SetLevel(logrus.ErrorLevel)
	//logger.Errorln("hello")

	//logger.SetLevel(logrus.WarnLevel)
	//logger.Warnln("hello")

	//logger.SetLevel(logrus.TraceLevel)
	//logger.Traceln("hello")

	//loggerOut := CreateLoggerInfo()
	//loggerOut := CreateLoggerWarn()
	//loggerOut := CreateLoggerError()
	//loggerOut := CreateLoggerDebug()
	loggerOut := CreateLoggerTrace()
	loggerOut("hello")
}